package pinboard.dataLayer.binPack;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Array;

import pinboard.dataLayer.ByteArrayConvert;
import pinboard.dataLayer.RefBag;
import pinboard.dataLayer.potocol.Guid;

public abstract class DefaultBinSerializer implements IBinSerializer {
    @Override
    public abstract byte[] toBytes(Object input);

    @Override
    public byte[] toBytes(Object[] input) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            baos.write(ByteArrayConvert.int2Bytes(input.length));
            for (int i = 0; i < input.length; i++) {
                baos.write(toBytes(input[i]));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return baos.toByteArray();
    }

    @Override
    public abstract Object toObject(byte[] input, RefBag<Integer> offset);

    @Override
    public abstract Object[] toArray(byte[] input, RefBag<Integer> offset);

    protected <T> T[] toArray(byte[] input, RefBag<Integer> offset, Class<T> tClass) {
        int len = ByteArrayConvert.bytes2Int(input, offset.data);
        offset.data = offset.data + 4;
        T[] result = (T[]) Array.newInstance(tClass, len);
        for (int i = 0; i < len; i++) {
            result[i] = (T) toObject(input, offset);
        }
        return result;
    }
}
